<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="deployTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.deployTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:deployment:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="todoList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="任务编号" align="center" prop="taskId"/>
      <el-table-column label="流程名称" align="center" prop="procDefName"/>
      <el-table-column label="当前节点" align="center" prop="taskName"/>
      <el-table-column label="流程版本" width="80" align="center">
        <template slot-scope="scope">
          <el-tag effect="plain" size="small" >v{{scope.row.procDefVersion}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="流程发起人" align="center">
        <template slot-scope="scope">
          <label v-if="scope.row.startUserName">{{scope.row.startUserName}} <el-tag effect="plain" type="info" size="mini">{{scope.row.startDeptName}}</el-tag></label>
          <el-tag v-else effect="plain" type="info" size="small">无发起人</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="接收时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="任务持续时间" align="center" prop="duration" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.assigneeId"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleProcess(scope.row)"
          >办理
          </el-button>
          <el-button
            v-else
            size="mini"
            type="text"
            icon="el-icon-s-claim"
            @click="handleClaim(scope.row)"
          >认领并办理
          </el-button>
<!--          <template v-if="scope.row.delegationState && scope.row.delegationState === 'RESOLVED'" >-->
            <el-button
              v-if="scope.row.claimTime"
              size="mini"
              type="text"
              icon="el-icon-s-release"
              @click="handleUnClaim(scope.row)"
            >取消认领
            </el-button>
<!--          </template>-->
          <template v-if="scope.row.multiInstance">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-plus-outline"
              @click="handleAddMulti(scope.row)"
            >加签
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-remove-outline"
              @click="handleDeleteMulti(scope.row)"
            >减签
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--多实例加签-->
    <el-dialog title="加签人员" :visible.sync="addMultiOpen" width="60%" :destroy-on-close="true" append-to-body>
      <flow-users v-if="addMultiOpen" @handleAssignSelect="addMultiUserSelect"/>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="addMultiOpen = false">取 消</el-button>
        <el-button size="small" type="primary" @click="addMultiUserComplete">确 定</el-button>
      </span>
    </el-dialog>

    <!--多实例减签-->
    <el-dialog title="减签人员" :visible.sync="deleteMultiOpen" width="60%" :destroy-on-close="true" append-to-body>
      <el-table ref="dataTable" v-loading="loading" :row-key="getRowKey" :data="userList" @selection-change="deleteMultiUserSelect">
        <el-table-column type="selection" :reserve-selection="true" width="50" align="center" />
        <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
        <el-table-column label="用户姓名" align="center" key="userName" prop="userName"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="deleteMultiOpen = false">取 消</el-button>
        <el-button size="small" type="primary" @click="deleteMultiUserComplete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  todoList,
  claimTask,
  unClaimTask,
  delDeployment,
  addMultiInstanceExecution,
  getMultiUserList,
  deleteMultiInstanceExecution
} from "@/api/flowable/todo";
import FlowUsers from "@/components/Flow/Task/User/index";
import {assignSelect} from "@/views/flowable/common/AssignUtils";

export default {
  name: "Deploy",
  components: {FlowUsers},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程待办任务表格数据
      todoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 多实例加签
      addMultiOpen: false,
      addMultiUserList: [],
      // 多实例减签
      deleteMultiOpen: false,
      deleteMultiUserList: [],
      userList: [],
      taskForm: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      todoList(this.queryParams).then(response => {
        this.todoList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 跳转到处理页面
    handleProcess(row){
      this.$router.push({ path: '/flowable/task/todo/detail/index',
        query: {
          procInsId: row.procInsId,
          executionId: row.executionId,
          deployId: row.deployId,
          taskId: row.taskId,
          taskName: row.taskName,
          procDefName: row.procDefName,
          startUser: row.startUserName + '-' + row.startDeptName,
          currentKey: row.taskDefKey,
        }})
    },
    // 认领/签收任务并跳转到处理页面
    handleClaim(row) {
      claimTask({taskId: row.taskId}).then(res => {
        if (res.code === 200) {
          this.$router.push({
            path: '/flowable/task/todo/detail/index',
            query: {
              procInsId: row.procInsId,
              executionId: row.executionId,
              deployId: row.deployId,
              taskId: row.taskId,
              taskName: row.taskName,
              procDefName: row.procDefName,
              startUser: row.startUserName + '-' + row.startDeptName,
              currentKey: row.taskDefKey,
            }
          })
        }
      }).catch(() => {
        this.$modal.msgError("认领/签收任务失败");
      })
    },

    // 取消认领/签收任务
    handleUnClaim(row) {
      unClaimTask({taskId: row.taskId}).then(res => {
        this.$modal.msgSuccess("取消认领/签收任务成功");
        this.getList();
      }).catch(() => {
        this.$modal.msgError("取消认领/签收任务失败");
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.taskId || this.ids;
      this.$confirm('是否确认删除流程定义编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delDeployment(ids);
      }).then(() => {
        this.getList();
       this.$modal.msgSuccess("删除成功");
      })
    },

    /** 多实例加签 */
    handleAddMulti(row) {
      this.addMultiOpen = true;
      this.taskForm = row;
    },

    /** 多实例减签 */
    handleDeleteMulti(row) {
      getMultiUserList({taskId: row.taskId}).then(res => {
        if (res.code === 200) {
          this.deleteMultiOpen = true;
          this.userList = res.data;
          this.taskForm.taskId = row.taskId;
        } else {
          this.$modal.msgError(res.msg);
        }
      })
    },

    /** 选择多实例加签用户 */
    addMultiUserSelect(selection) {
      if (selection) {
        this.addMultiUserList = JSON.parse(JSON.stringify(assignSelect("users", "", selection)));
      }
    },

    /** 提交多实例加签用户 */
    addMultiUserComplete() {
      this.taskForm.multiUserList = this.addMultiUserList.map(item => ({ userId: item.id, userName: item.name }));
      addMultiInstanceExecution(this.taskForm).then(res => {
        if (res.code === 200) {
          this.taskForm = {};
          this.addMultiOpen = false;
          this.$modal.msgSuccess("加签成功!");
        } else {
          this.$modal.msgError(res.msg);
        }
      })
    },


    /** 选择多实例减签用户 */
    deleteMultiUserSelect(selection) {
      if (selection) {
        this.deleteMultiUserList = JSON.parse(JSON.stringify(selection));
      }
    },

    /** 提交多实例减签用户 */
    deleteMultiUserComplete() {
      this.taskForm.multiUserList = this.deleteMultiUserList;
      deleteMultiInstanceExecution(this.taskForm).then(res => {
        if (res.code === 200) {
          this.taskForm = {};
          this.deleteMultiOpen = false;
          this.$modal.msgSuccess("减签成功!");
        } else {
          this.$modal.msgError(res.msg);
        }
      })
    },

    // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
    getRowKey (row) {
      return row.userId
    },
  }
};
</script>

